package team.kirohuji.controller.attendance;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import team.kirohuji.domain.attendance.AttendanceRecord;
import team.kirohuji.repository.jpa.attendance.AttendanceRecordRepository;
import team.kirohuji.service.attendance.AttendanceRecordService;

@RestController
@RequestMapping("/attendance/record")
public class AttendanceRecordController {
	private static final Logger logger = LoggerFactory.getLogger(AttendanceController.class);
	
	@Resource
	public AttendanceRecordService attendanceRecordService;
	
	@Autowired
	public AttendanceRecordRepository attendanceRecordRepository;

	/**
	 * Returns the number of entities available. 返回总记录数
	 * 
	 * @return the number of entities
	 */
	/*
	 * @RequestMapping(value = "/count", method = RequestMethod.GET, produces =
	 * "text/plain;charset=UTF-8")
	 */
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	long count() {
		return attendanceRecordRepository.count();
	}

	/**
	 * Deletes the entity with the given id. 根据给出的id删除记录
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @throws IllegalArgumentException
	 *             in case the given {@code id} is {@literal null}
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	void delete(@PathVariable Integer id) {
		attendanceRecordRepository.deleteById(id);
	}

	/**
	 * Deletes a given entity. 根据给出的实体删除记录
	 * 
	 * @param entity
	 * @throws IllegalArgumentException
	 *             in case the given entity is (@literal null}.
	 */
	@RequestMapping(value = "", method = RequestMethod.DELETE)
	void delete(@RequestBody AttendanceRecord entity) {
		attendanceRecordRepository.delete(entity);
	}

	/**
	 * Deletes the given entities. 根据给出的一组实体删除一组记录
	 * 
	 * @param entities
	 * @throws IllegalArgumentException
	 *             in case the given {@link Iterable} is (@literal null}.
	 */
	@RequestMapping(value = "/group", method = RequestMethod.DELETE)
	void delete(@RequestBody List<AttendanceRecord> entities) {
		attendanceRecordRepository.deleteAll(entities);
	}

	/**
	 * Deletes all entities managed by the attendanceRecordRepository. 根据repository 删除所有的记录
	 */
	@RequestMapping(value = "/all", method = RequestMethod.DELETE)
	void deleteAll() {
		attendanceRecordRepository.deleteAll();
	}

	/**
	 * Deletes all entites in a batch call. 删除所有实体记录
	 */
	void deleteAllInBatch() {
		attendanceRecordRepository.deleteAllInBatch();
	}

	/**
	 * Deletes the given entities in a batch which means it will create a single
	 * {@link Query}. Assume that we will clear the
	 * {@link javax.persistence.EntityManager} after the call. 进行批量删除
	 * 
	 * @param entities
	 */
	void deleteInBatch(@RequestBody List<AttendanceRecord> entities) {
		attendanceRecordRepository.deleteInBatch(entities);
	}

	/**
	 * Returns whether an entity with the given id exists. 根据给出的id判断对应的实体记录是否存在
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @return true if an entity with the given id exists, {@literal false}
	 *         otherwise
	 * @throws IllegalArgumentException
	 *             if {@code id} is {@literal null}
	 */
	@RequestMapping(value = "/exists/{id}", method = RequestMethod.GET)
	boolean exists(@PathVariable Integer id) {
		return attendanceRecordRepository.existsById(id);
	}

	/**
	 * Returns all instances of the type. 返回所有的实体记录
	 * 
	 * @return all entities
	 */
	@RequestMapping(value = "/group", method = RequestMethod.GET)
	List<AttendanceRecord> findAll() {
		return attendanceRecordRepository.findAll();
	}

	/**
	 * Returns all instances of the type with the given IDs. 根据给出的一组id值返回所有对应的实体记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/group/{ids}", method = RequestMethod.GET)
	List<AttendanceRecord> findAll(String ids) {
		String[] register = ids.split(";");
		List<String> strList = Arrays.asList(register);
		List<Integer> intList = new ArrayList<Integer>();
		for (String str : strList) {
			intList.add(Integer.parseInt(str));
		}
		return attendanceRecordRepository.findAllById(intList);
	}

	/**
	 * Returns all entities sorted by the given options. 根据给出的参数返回所有实体记录
	 * 
	 * @param sort
	 * @return all entities sorted by the given options
	 */
	/* @RequestMapping(value = "", method = RequestMethod.GET) */
	/* List<AttendanceRecord> findAll(Sort sort); */
	/*
	 * List<AttendanceRecord> findAll(
	 * 
	 * @RequestParam(value = "sortby", required=false,defaultValue = "5") String
	 * sortby,
	 * 
	 * @RequestParam(value = "order", required=false,defaultValue = "5") String
	 * order);
	 */
	/**
	 * Returns a {@link Page} of entities meeting the paging restriction provided in
	 * the {@code Pageable} object. 分页获取数据
	 * 
	 * 分页获取数据
	 * 
	 * @param page
	 *            第几页
	 * @param limit
	 *            每页最长记录数
	 * @return a page of entities
	 */
	@RequestMapping(value = "/page/{activePage}", method = RequestMethod.GET)
	/* Page<AttendanceRecord> findAll(Pageable pageable) */
	Page<AttendanceRecord> findAll(@PathVariable(required = false) Integer activePage,
			@RequestParam(value = "limit", defaultValue = "5") Integer limit) {
		if(activePage!=0||activePage!=null) {
			Sort sort = new Sort(Direction.DESC, "attendanceRecordId");
			Pageable pageable = new PageRequest(activePage, limit, sort);
			return attendanceRecordRepository.findAll(pageable);
		}else {
			Sort sort = new Sort(Direction.DESC, "attendanceRecordId");
			Pageable pageable = new PageRequest(0, limit, sort);
			return attendanceRecordRepository.findAll(pageable);
		}
	}

	/*
	 * List<AttendanceRecord> findAll(){
	 * 
	 * List<AttendanceRecord> findAll(Sort sort);
	 * 
	 * List<AttendanceRecord> findAll(Iterable<Integer> ids);
	 */

	/**
	 * Retrieves an entity by its id. 根据id取得对应的一个实体记录
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @return the entity with the given id or {@literal null} if none found
	 * @throws IllegalArgumentException
	 *             if {@code id} is {@literal null}
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	AttendanceRecord findOne(@PathVariable Integer id) {
		return attendanceRecordRepository.getOne(id);
	}

	/**
	 * Flushes all pending changes to the database. 刷新所有到数据库的改变
	 */
	@RequestMapping(value = "/flush", method = RequestMethod.GET)
	void flush() {
		attendanceRecordRepository.flush();
	}

	/**
	 * Returns a reference to the entity with the given identifier. 根据给出的id获得一个实体记录
	 * 
	 * @param id
	 *            must not be {@literal null}.
	 * @return a reference to the entity with the given identifier.
	 * @see EntityManager#getReference(Class, Object)
	 */
	/* AttendanceRecord getOne(Integer id); */

	/**
	 * Saves a given entity. Use the returned instance for further operations as the
	 * save operation might have changed the entity instance completely.
	 * 保存给出的一个实体，如果实体存在则实体记录会被修改记录，不存在则保存
	 * 
	 * @param entity
	 * @return the saved entity
	 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	AttendanceRecord save(@RequestBody AttendanceRecord entity) {
		return attendanceRecordRepository.save(entity);
	}

	/**
	 * Saves all given entities. 保存给出的一组实体记录
	 * 
	 * @param entities
	 * @return the saved entities
	 * @throws IllegalArgumentException
	 *             in case the given entity is (@literal null}.
	 */
	@RequestMapping(value = "/group", method = RequestMethod.POST)
	List<AttendanceRecord> save(@RequestBody List<AttendanceRecord> entities) {
		return attendanceRecordRepository.saveAll(entities);
	}

	/**
	 * Saves an entity and flushes changes instantly. 保存实体记录并且立刻刷新
	 * 
	 * @param entity
	 * @return the saved entity
	 */
	AttendanceRecord saveAndFlush(AttendanceRecord entity) {
		return attendanceRecordRepository.saveAndFlush(entity);
	}
}
